import React, { createContext, useContext, useState, ReactNode } from 'react';

interface Settings {
  language: string;
  theme: 'light' | 'dark' | 'system';
  mapType: 'standard' | 'satellite' | 'terrain';
  notifications: {
    push: boolean;
    sound: boolean;
    email: boolean;
  };
  translation: {
    autoDetect: boolean;
    defaultSourceLang: string;
    defaultTargetLang: string;
  };
  offline: {
    autoDownload: 'always' | 'wifi' | 'never';
    maxStorage: number; // in MB
  };
  location: {
    enabled: boolean;
    precision: 'high' | 'medium' | 'low';
  };
}

interface SettingsContextType {
  settings: Settings;
  updateSettings: (updates: Partial<Settings>) => void;
  resetSettings: () => void;
}

const defaultSettings: Settings = {
  language: 'zh-CN',
  theme: 'system',
  mapType: 'standard',
  notifications: {
    push: true,
    sound: true,
    email: false
  },
  translation: {
    autoDetect: true,
    defaultSourceLang: 'zh',
    defaultTargetLang: 'en'
  },
  offline: {
    autoDownload: 'wifi',
    maxStorage: 1024 // 1GB
  },
  location: {
    enabled: true,
    precision: 'high'
  }
};

const SettingsContext = createContext<SettingsContextType | undefined>(undefined);

export const useSettings = () => {
  const context = useContext(SettingsContext);
  if (context === undefined) {
    throw new Error('useSettings must be used within a SettingsProvider');
  }
  return context;
};

interface SettingsProviderProps {
  children: ReactNode;
}

export const SettingsProvider: React.FC<SettingsProviderProps> = ({ children }) => {
  const [settings, setSettings] = useState<Settings>(() => {
    // 从 localStorage 加载设置
    const savedSettings = localStorage.getItem('app-settings');
    if (savedSettings) {
      try {
        return { ...defaultSettings, ...JSON.parse(savedSettings) };
      } catch (error) {
        console.error('Failed to parse saved settings:', error);
        return defaultSettings;
      }
    }
    return defaultSettings;
  });

  const updateSettings = (updates: Partial<Settings>) => {
    const newSettings = { ...settings, ...updates };
    setSettings(newSettings);
    localStorage.setItem('app-settings', JSON.stringify(newSettings));
  };

  const resetSettings = () => {
    setSettings(defaultSettings);
    localStorage.setItem('app-settings', JSON.stringify(defaultSettings));
  };

  const value: SettingsContextType = {
    settings,
    updateSettings,
    resetSettings
  };

  return (
    <SettingsContext.Provider value={value}>
      {children}
    </SettingsContext.Provider>
  );
};